package com.abigdreamer.im.server.module;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.abigdreamer.im.server.log.EIMLogger;
import com.abigdreamer.im.server.module.socketHandler.FileSocketHandler;
import com.abigdreamer.im.server.serverConfig.Config;
import com.abigdreamer.im.server.serverConfig.EIMFileSocketConfig;

/**
 * 服务器端文件传输Socket负责把收到到的文件包转发到目标用户
 */

public class EIMFileSocket extends EIMSocket implements ISockect {

	private EIMFileSocketConfig fileSocketConfig;

	public EIMFileSocket(EIMFileSocketConfig config) {
		this.fileSocketConfig = config;
	}

	public boolean initSocket(Config config) {
		EIMLogger.INFO("正在初始化 文件服务Socket");
		EIMFileSocketConfig fileConfig = (EIMFileSocketConfig) config;
		this.setSocket_IP(fileConfig.getIp());
		EIMLogger.INFO("正在初始化 文件服务Socket的Ip");
		this.setSocket_port(fileConfig.getPost());
		EIMLogger.INFO("正在初始化 文件服务Socket的端口");
		this.setHandlerAdapter(new FileSocketHandler());
		EIMLogger.INFO("正在初始化 文件服务Socket的处理器");
		this.setAcceptor(new NioSocketAcceptor());
		EIMLogger.INFO("正在初始化 文件服务Socket的接收器");

		EIMLogger.INFO("初始化了文件服务Socket");
		EIMLogger.INFO("文件Socket服务IP:" + this.getSocket_IP());
		EIMLogger.INFO("文件Socket服务端口号:" + this.getSocket_port());
		return true;
	}

	public boolean startSocket() {

		boolean result = false;
		if (this.isStart() == false) {
			initSocket(this.fileSocketConfig);
			DefaultIoFilterChainBuilder chain = this.getAcceptor().getFilterChain();
			ObjectSerializationCodecFactory objscf = new ObjectSerializationCodecFactory();
			ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(objscf);
			chain.addLast("myfileChain", protocolCodecFilter);
			this.getAcceptor().setHandler(this.getHandlerAdapter());
			try {
				this.getAcceptor().bind(new InetSocketAddress(this.getSocket_IP(), this.getSocket_port()));
				this.setStart(true);
				result = true;
				EIMLogger.INFO("成功启动了文件服务Socke");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public boolean closeSocket() {
		this.getAcceptor().dispose();
		this.setStart(false);
		EIMLogger.INFO("关闭了文件服务Socket");
		return true;
	}
}
